const CalendarIdRegex = /cal:(\w*)/;
const CalendarFileRegex = /f\s*=\s*(?:"([^"]+)"|([^\s\]]+))/;
const CalendarTitleRegex = /t=([^\s]+)/;
const CalendarDirRegex = /d=([\w\-\._%]+)/;

import * as vscode from 'vscode';
import fs from 'fs';
import path from 'path';

export class CalendarBlock {

    public RawText: string;
    public static BlockTag = 'calendar';
    private converter!: (text: string) => number;
    public title: string = '';

    constructor(text: string) {
        this.RawText = text;

        this.build();
    }

    public static isCalendarBlock(text: string) {
        return text.startsWith('[cal:') && text.endsWith(']');
    }

    public id: string = '';
    public isValid: boolean = true;

    /**
     * 构建日历块的核心逻辑
     * 
     * 该方法负责解析原始文本，提取日历ID、JS文件和标题信息，
     * 并尝试加载和执行指定的JS文件内容。如果任何步骤失败，
     * 会将isValid标记为false。
     * 
     * @private
     * 内部实现细节，不对外暴露
     * 
     * @throws 当JS文件无效或加载失败时抛出错误
     */
    private build() {
        const noWrapText = this.RawText.substring(1, this.RawText.length - 1);

        try {
            this.id = CalendarIdRegex.exec(noWrapText)?.[1] || '';
            if (!this.id) {
                this.isValid = false;
                return;
            }

            const _jsfile = CalendarFileRegex.exec(noWrapText)?.filter(item=>item)[1];

            if (_jsfile) {

            }else {
                throw new Error('未找到js文件');
            }

            const dir = CalendarDirRegex.exec(noWrapText)?.[1];
            let rootPath = decodeURIComponent(dir || '');
            let jsfile = path.join(rootPath, _jsfile);

            console.log('folders:', vscode.workspace.workspaceFolders);
            console.log('rootPath:', rootPath);
            const topFolder = vscode.workspace.workspaceFolders
                ?.filter(item => rootPath.startsWith(item.uri.fsPath));
            console.log('topFolder:', topFolder);

            let shared = false;
            if (topFolder && topFolder.length > 0) {
                const mainPath = topFolder[0].uri.fsPath;
                while (rootPath.startsWith(mainPath)) {
                    console.log('rootPath:', rootPath);
                    if (!fs.existsSync(jsfile)) {
                        if (!shared) {
                            shared = true;
                            // 用于补充搜索本级Shared目录
                        }else {
                            rootPath = path.dirname(rootPath);
                        }
                        jsfile = path.join(rootPath, 'shared',_jsfile);

                    } else {
                        break;
                    }
                }
                if (!fs.existsSync(jsfile)) {
                    vscode.window.showErrorMessage(`未找到${_jsfile}`);
                    throw new Error();
                }
            }else {
                vscode.window.showErrorMessage(`检索范围内未检测到${_jsfile}`);
                throw new Error();
            }


            console.log('build calendar block');
            console.log(this.RawText);
            console.log(rootPath,jsfile);

            this.title = CalendarTitleRegex.exec(noWrapText)?.[1]!;

            // 读取jsfile内容
            const jscontent = jsfile ? fs.readFileSync(jsfile, 'utf-8') : '';
            console.log(jscontent);

            if (jscontent) {
                this.converter = eval(`(()=> { return ${jscontent}})()`);
                console.log('converter', this.converter);
            }else {
                throw new Error('Invalid jsfile');
            }

        } catch (error) {
            this.isValid = false;
            console.log(error);
            vscode.window.showErrorMessage(`日历转换器加载失败：${this.RawText}`);
        }

    }

    /**
     * 将输入的文本通过转换器进行处理并返回结果
     * @param text - 需要转换的文本内容
     * @returns 转换后的文本结果
     */
    public convert(text: string) {
        return this.converter(text);
    }

}

